package org.snail.admin.backend.controller;


import org.snail.admin.backend.dto.LoginRequest;
import org.snail.admin.backend.dto.ResponseResult;
import org.snail.admin.backend.utils.JwtUtils;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.AuthenticationException;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.HashMap;
import java.util.Map;


@RestController
public class AuthController {

    private static final Logger logger = LoggerFactory.getLogger(AuthController.class);

    private final AuthenticationManager authenticationManager;

    public AuthController(AuthenticationManager authenticationManager) {
        this.authenticationManager = authenticationManager;
    }

    @PostMapping("/login")
    public ResponseResult<Map<String, String>> login(@RequestBody LoginRequest loginRequest) {
        try {
            UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(loginRequest.username(), loginRequest.password());
            authenticationManager.authenticate(authenticationToken);
            logger.info("User {} authenticated successfully", loginRequest.username());

            String token = JwtUtils.generateToken(loginRequest.username());
            
            Map<String, String> data = new HashMap<>();
            data.put("token", token);
            
            return ResponseResult.success(data);
        } catch (AuthenticationException e) {
            logger.error("Authentication failed for user {}: {}", loginRequest.username(), e.getMessage());
            return ResponseResult.error(401, "用户名或密码错误");
        }
    }
}